$(function () {
  //var imgArr = [{ image_url: './img/loading.png', id: 3, status: 2 }];
  // createHtml(imgArr);
  var imageId = null;
  /*页面一进来，调用的接口，获取图片数据*/
  init();
  function init() {
    $.ajax({
      url: './i/home/image/lastimagelist',
      type: 'GET',
      error: function (error) {
      },
      success: function (data) {
        if (data.error_code != 0) {
          alert(data.error_msg);
        } else if (data.error_code == 0 && data.error_msg == 'ok') {
          status = data
          var imgArr = [];
          var lastData = data.data;
          createHtml(lastData);
          // console.log('lastData', lastData);
        }
      }
    })
  }
  //createHtml(imgArr);

  /*图片点击事件绑定*/
  $(".middle").on('click', function (e) {
    var $this = $(this);
    var $target = $(e.target);
    var img_groups = $this.find('img');
    imageId = $target.data('id');
    if (!imageId) {
      return;
    }
    if (img_groups && img_groups.length >= 0) {
      for (var i = 0, len = img_groups.length; i < len; i++) {
        var $item = $(img_groups[i]);
        if ($item.data('id') != imageId) {
          $item.css({
            border: 'none'
          })
        } else {
          $target.css({
            border: '1px solid red'
          })
        }
      }
    }
  })

  /*点击识别按钮事件绑定*/
  $(".recognition_container").click(function () {
    if (!imageId) {
      alert('请先选择需要识别的图片，一次一张');
      return;
    }
    $.ajax({
      url: './i/home/image/imagerecognition',
      type: 'POST',
      data: { imageId: parseInt(imageId) },
      error: function (error) {

      },
      success: function (data) {
        if (data.error_code == 0) {
          var status = data.data;
          if(status == 2 || status ==4 || status==5 ) {
              alert('图片识别成功，确定后跳转');
              window.location.href = './recognition.html?imageId=' + imageId
          } else {
              if (status == 1) {
                  alert('识别中,请3-4分钟后再次点击“识别”按钮，查看识别结果');
              }
              if (status == 3) {
                  alert('识别失败');
              }
          }
        } else {
          alert(data.error_msg);
        }
      }
    })


  })

  // $.ajax({
  //   url: 'http://www.oct.ai/i/home/image/getlastrecognition',
  //   type: 'POST',
  //   data: { imageId: parseInt(imageId) },
  //   error: function (error) { },
  //   success: function (data) {
  //     if (data.error_code != 0) {
  //       alert(data.error_msg)
  //     } else {

  //       /*成功后，更新图片*/
  //       var $recognition_pic = $('.recognition_pic'), $origin_pic = $('.origin_pic');
  //       $recognition_pic.css({
  //         background: 'url(' + data.data.content + ') center top no-repeat',
  //         backgroundSize: '100% 100%'
  //       });
  //       $origin_pic.css({
  //         background: 'url(' + data.data.image_url + ') center top no-repeat',
  //         backgroundSize: '100% 100%'
  //       })
  //       setTimeout(function () {
  //         if (data.data.recognition_ret == 1) {
  //           alert("您好，未发生病变");
  //         }
  //       }, 1000)
  //       rid = data.data.id;
  //       remark = data.data.ratification_content;
  //       content = data.data.oppugn_content;
  //       status = data.data.status;
  //     }
  //   }
  // })

  /*点击上传绑定事件*/
  var pic_upload = document.getElementById('pic_upload'), lastResult = [];
  if (typeof FileReader === 'undefined') {
    alert("抱歉，你的浏览器不支持 FileReader，无法上传文件");
    pic_upload.setAttribute('disabled', 'disabled');
  } else {
    pic_upload.addEventListener('change', readFile, false);
  }
  function readFile() {
    if (!pic_upload['value'].match(/.jpg|.gif|.jpeg|.png|.bmp/i)) {
      //判断上传文件格式
      alert("上传的图片格式不正确，请重新选择");
      return;
    }
    // var formData = new FormData();
    // var imgFileValue = $("#pic_upload")[0].files[0];
    // formData.append('imgFileValue', imgFileValue);
    // console.log('imgFileValue', imgFileValue, formData);
    // $.ajax({
    //   url: 'http://www.oct.ai/i/home/image/upload',
    //   type: 'POST',
    //   data: formData,
    //   processData: false,
    //   contentType: false,
    //   error: function(error) {

    //   },
    //   success: function(data) {
    //     if (data.error_code !=0) {
    //       alert(data.error_msg);
    //     } else {
    //       console.log(111, data.data);
    //     }
    //   }
    // })

    for (var i = 0; i < this.files.length; i++) {
      var targetFile = this.files[i];
      var formData = new FormData();
      formData.append('file', targetFile)
      var reader = new FileReader();
      //console.log('targetFile', formData);
      //reader.readAsDataURL(targetFile);
      //reader.onload = function (e) {
      $.ajax({
        url: './i/home/image/upload',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        error: function (error) {

        },

        success: function (data) {
          if (data.error_code != 0) {
            alert(data.error_msg);
          } else {
            init();
          }
        }
      })
      //}
    }
  }

  /*轮播图部分构建函数*/
  function createHtml(data) {
    var str = '';
    var $container = $('.middle');
    if (data.length == 0) {
      str += '<div class="nothing_container">~您暂时没有可展示的图片，请点击上传~</div>'
    } else if (data.length == 1) {
      var className = '';
      if (data[0].status == 2) {
        className = 'recognitioned'
      }
      str += '<div class="single_container ' + className + '">' +
        '<img src=' + data[0].image_url + ' data-id=' + parseInt(data[0].id) + ' data-status='+ parseInt(data[0].status) +'>'
        + '</div>'
    } else if (data.length == 2) {
      var className1 = '', className2='';
      if (data[0].status == 2) {
        className1 = 'recognitioned'
      }
      if (data[1].status == 2) {
        className2 = 'recognitioned'
      }
      str += '<div class="double_groups">' +
        '<div class="double_container ' + className1 + '">' +
        '<img src=' + data[0].image_url + ' data-id=' + parseInt(data[0].id) + ' data-status=' + parseInt(data[0].status) + '>' +
        '</div>' +
        '<div class="double_container '+ className2 +'">' +
        '<img src=' + data[1].image_url + ' data-id=' + parseInt(data[1].id) + ' data-status=' + parseInt(data[1].status) + '>' +
        '</div>' +
        '</div>'

    } else {
      str += '<div class="swiper-container">' +
        '<div class="swiper-wrapper">'
      data.forEach(function (item, index) {
        var className = '';
        if (item.status == 2) {
          className = 'recognitioned'
        }
        str += '<div class="swiper-slide '+ className +'">' +
          '<img alt="" src=' + item.image_url + ' data-id=' + parseInt(item.id) + ' data-status=' + parseInt(item.status) + '>' +
          '</div>'
      })
      str += '</div>';
      str += '<div class="swiper-pagination"></div>'
      str += '</div>';
      str += '<div class="swiper-button-next next_special"></div><div class="swiper-button-prev prev_special"></div>'
    }
    $container.html(str);
    if (data.length >= 3) {
      var swiper = new Swiper('.swiper-container', {
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
        slidesPerView: 3,
        spaceBetween: 15,
        pagination: {
          el: '.swiper-pagination',
          clickable: true,
        },
      });
    }
    var slider_width = $('.swiper-slide').width(), slider_height = $('.swiper-slide').height(), ratio = 467 / 385;
    var last_width = slider_width, last_height = slider_height;
    if (slider_width / slider_height >= ratio) {
      last_width = last_height * ratio;
    } else {
      last_height = last_width / ratio;
    }
    $('.swiper-slide img').css({
      width: last_width,
      height: last_height,
      top: (slider_height - last_height) / 2
    })
  }

  $(".footer_buttons .prev_page").click(function () {
    window.history.go(-1);
  });
  $(".footer_buttons .next_page").click(function () {
    window.location.href = './home.html';
  });

  $(window).resize(function () {
    var $this = $(this);
    var slider_width = $('.swiper-slide').width(), slider_height = $('.swiper-slide').height(), ratio = 467 / 385;
    var last_width = slider_width, last_height = slider_height;
    if (slider_width / slider_height >= ratio) {
      last_width = last_height * ratio;
    } else {
      last_height = last_width / ratio;
    }
    $('.swiper-slide img').css({
      width: last_width,
      height: last_height,
      top: (slider_height - last_height) / 2
    })
  })
})